/**
 * 广发银行，公共变量、公共业务处理
 */
//初始信用卡数量
var credit_num=0;

//初始借记卡数量
var debit_num=0;

//信用卡集合
var listC = new ArrayList();

//借记卡集合
var listD = new ArrayList();

//月账单集合
var monthBill = new LinkedHashMap();

//用于存放基础信息
var baseMap=new HashMap();

var card = 0;
var card_Id = 1;
var bill_ShoppingSheet_Id = 1;
var bill_ID = 1;
var billId = 0;

//定义卡类型
var card_type={
    //广发银行，信用卡标识为"30"
    CREDIT:"30"
}

//定义货币类型
var currency_Type={
    RMB:"156",
    USD:"840"
}

//定义全局使用到的URL
var urls={
    //官网首页
    INDEX_URL:"https://ebanks.cgbchina.com.cn/perbank/",
    SESSIONDATA_URL:"https://ebanks.cgbchina.com.cn/perbank/sessionData.do",
    USERINFO_URL : "https://ebanks.cgbchina.com.cn/perbank/ECAD0003.do",
    CRTBILL_URL : "https://ebanks.cgbchina.com.cn/perbank/CR1001.do",
    //已出账单
    BILLMAIN_URL : "https://ebanks.cgbchina.com.cn/perbank/CR1080.do",
    DETAIL_URL : "https://ebanks.cgbchina.com.cn/perbank/CR0002.do",
    SELECTED_URL : "https://ebanks.cgbchina.com.cn/perbank/mvcAccess.do",
    //卡信息，当天未出账单购物明细
    CARDINFO_URL_0:"https://ebanks.cgbchina.com.cn/perbank/CR0132.do",
    CARDINFO_URL_1:"https://ebanks.cgbchina.com.cn/perbank/CR0002.do",
    //借记卡信息
    DEBIT_CARDINFO_0:"https://ebanks.cgbchina.com.cn/perbank/AC0002.do",
    //借记卡已出账单信息
    DONE_INFO_0:"https://ebanks.cgbchina.com.cn/perbank/AC0003.do"
}

var saveType = new LinkedHashMap();
{
    saveType.put("YSV", "活期");
    saveType.put("YTM", "整存整取");
    saveType.put("YNT", "通知存款");
    saveType.put("ATF", "丰收优利");
    saveType.put("YTD", "定活智能通");
}
var savePeroid = new LinkedHashMap();
{
    savePeroid.put("201", "1-MONTH");
    savePeroid.put("203", "3-MONTH");
    savePeroid.put("206", "6-MONTH");
    savePeroid.put("301", "1-YEAR");
    savePeroid.put("302", "2-YEAR");
    savePeroid.put("303", "3-YEAR");
    savePeroid.put("305", "5-YEAR");
    savePeroid.put("308", "8-YEAR");
    savePeroid.put("101", "1-DAY");
    savePeroid.put("107", "7-DAY");
    savePeroid.put("213", "13-MONTH");
    savePeroid.put("214", "14-MONTH");
    savePeroid.put("215", "15-MONTH");
    savePeroid.put("218", "18-MONTH");
    savePeroid.put("220", "20-MONTH");
    savePeroid.put("221", "21-MONTH");
    savePeroid.put("230", "30-MONTH");
}

//统一定义日志打印
var log_print={

}



/**
 * 卡遍历时使用的计数方法
 */
function nextCard() {
    card++;
    card_Id = 1;
    bill_ShoppingSheet_Id = 1;
    bill_ID = 1;
}


/**
 * 抓取登录成功后的首页内容
 */
function crawlIndex(){
    var indexPage = get_html();
    // get_html属于异常操作，睡眠3秒，使得首页充分加载
    Thread.sleep(3000);
    storeDataToFile(context, indexPage, "indexPage.html")
    logger.info("任务【{}】，广发登录首页内容抓取完成",context.get(LUA_TASK_KEY));
    context.put(keys.INDEX_PAGE,indexPage);
}

/**
 * 解析首页，获取_emp_sid
 */
function parseIndex(){
    try{
        var indexPage=context.get(keys.INDEX_PAGE);
        var EMP_SID = parseEmpSid(indexPage);

        if (EMP_SID == null) {
            logger.error(BankCode.CGB + " 获取用户ID失败 taskkey {}",context.get(Constants.LUA_TASK_KEY));
            throw new BankException(BankConstants.BALO_99601_40, "获取用户ID失败");
        }
        baseMap.put(keys.EMP_SID,EMP_SID);
    }catch(e){
        logger.error("taskKey={} 获取用户ID异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtExceptionByJS(context, e);
    }
}

/**
 * 抓取卡信息页面
 */
function crawlSessionInfo() {
    try{
        var EMP_SID=baseMap.get(keys.EMP_SID);
        var paramsMap = new HashMap();
        paramsMap.put("EMP_SID", EMP_SID.trim());
        logger.info(BankCode.CGB + " 获取session开始 taskkey {}",context.get(Constants.LUA_TASK_KEY));
        //拼接需要请求的url
        var url = generateURL(urls.SESSIONDATA_URL, paramsMap);
        var cardInfoHtml = ajax_get(url);
        Thread.sleep(5000);
        logger.info(BankCode.CGB + " 获取session结束 taskkey {}",context.get(Constants.LUA_TASK_KEY));
        storeDataToFile(context, cardInfoHtml, "session" + ".html")
        context.put(keys.SESSION_INFO,cardInfoHtml);
    }catch (e) {
        logger.error("taskKey={} 获取卡信息异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtExceptionByJS(context, e);
    }
}

/**
 * 解析卡信息
 */
function parseSessionInfo(){
    try{
        //从上下文中拿到卡信息
        var cardInfoHtml=context.get(keys.SESSION_INFO);

        var cardInfoObj = JSON.parseObject(cardInfoHtml);
        var cd = cardInfoObj.getJSONObject("cd");

        //信息都存在Json的cd中，如果cd为空，则视为没有查询到客户信息
        if(cd==null){
            throw new BankException(BankConstants.BALO_22107_10, "没有查询到客户信息");
        }

        var user_name = cd.getString("session_customerNameCN");// 姓名
        var user_mobile = cd.getString("session_mobileNo");// 真实手机号

        baseMap.put(keys.USER_NAME,user_name);
        baseMap.put(keys.USER_MOBILE,user_mobile);

        //解析账户信息数字，获取信息卡数量、借记卡数量及总量
        var session_iAccountInfoArray = cd.getJSONArray("session_iAccountInfo");

        //存入上下文，信用卡、借记卡处理都会用到
        context.put(keys.SESSION_INFO,session_iAccountInfoArray);

        logger.info(BankCode.CGB+"获取总卡数量:"+session_iAccountInfoArray.size()+" taskkey {} ",context.get(Constants.LUA_TASK_KEY));

        //信用卡数量
        var creditNum=0;

        //借记卡数量
        var debitNum=0;

        //遍历账户数组,计算卡数量
        for(var i=0;i<session_iAccountInfoArray.size();i++){
            var session_iAccountInfoObj=session_iAccountInfoArray.get(i);
            //存在卡信息
            if(session_iAccountInfoObj!=null){
                var accountType = session_iAccountInfoObj.getString("accountType");
                //信息卡计数
                if(card_type.CREDIT.equals(accountType)){
                    credit_num=++creditNum;
                }else{
                    debit_num=++debitNum;
                }
            }
        }

        //向上下文中设置信用卡数量
        context.put(keys.CRED_CARD_SIZE,credit_num);

        //向上下文中设置借记卡数量
        context.put(keys.DEBT_CARD_SIZE,debit_num);

    }catch(e){
        logger.error("taskKey={} 解析卡信息异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtExceptionByJS(context, e);
    }
}

/**
 * 实例化账单对象
 */
function getBillAllData(){
    var billAllData = new BillAllData();
    billAllData.setCashLimit(null);
    billAllData.setCreditLimit(null);
    billAllData.setInterest(null);
    billAllData.setLastBalance(null);
    billAllData.setLastPayment(null);
    billAllData.setMinPayment(null);
    billAllData.setNewBalance(null);
    billAllData.setNewCharges(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);
    return billAllData;
}

/**
 * 实例化账单详情对象
 * @returns {Expense}
 */
function getExpense(){
    var expense = new Expense();
    expense.setAmountMoney(null);
    expense.setBalance(null);
    return expense;
}

/**
 *  实例化f分期明细对象
 * @returns {Installment}
 */
function getInstallment(){
    var installment = new Installment();
    installment.setAmountMoney(null);
    installment.setHandingFee(null);
    installment.setTransferFee(null);
    return installment;
}

/**
 *  实例化存款对象
 * @returns {Installment}
 */
function getCreditCardTimeDeposit(){
    var creditCardTimeDeposit = new CreditCardTimeDeposit();
    creditCardTimeDeposit.setBalance(null);
    creditCardTimeDeposit.setInterest(null);
    creditCardTimeDeposit.setPeriod(null);
    return creditCardTimeDeposit;
}

/**
 * 将金额除100
 *
 * @param moneyStr
 * @return
 */
function moneyChu100( moneyStr) {
    var money = GetJiner(moneyStr);
    var d = money.doubleValue() / 100;
    return GetJiner(d + "");
}

/**
 * 根据账单月拼接账单日
 * @param bill_month
 * @returns {*}
 */
function getBillDate( bill_month) {
    if(bill_month!=null){
        bill_month = bill_month+"-01";
    }
    return bill_month;
}

/**
 * 金额格式处理
 * @param jiner
 * @returns {*}
 * @constructor
 */
function  GetJiner( jiner) {
    if (jiner == null || jiner.replaceAll("[^\\d]", "").equals("")) {
        return null;
    }

    if (jiner.contains("+")) {
        var jiners = jiner.split(/\+/);
        var d = 0;
        for each (var string in jiners) {
            d = d + GetJiner(string).doubleValue();
        }
        return GetJiner("" + d);
    }
    jiner = jiner.replaceAll("￥", "").trim();
    jiner = jiner.replaceAll("¥", "").trim();
    jiner = jiner.replaceAll("\\s*", "").trim();
    jiner = jiner.trim().equals("") ? "0" : jiner;
    var a = 0;
    jiner = jiner.trim();
    if (jiner.matches(".*?\\.\\d{1,}\u5143")) {
        var newjiner = jiner.replaceAll("(.*?\\.\\d{1,})\u5143", "$1");
        newjiner = newjiner.replaceAll("[^\\d\\.]", "");
        a = Double.parseDouble(newjiner);
    } else if (jiner.matches("\\d{1,}\\.\\d{1,}")) {
        a = Double.parseDouble(jiner);
    } else if (jiner.matches("\\d{1,}")) {
        a = Double.parseDouble(jiner);
    } else if (jiner.matches("(\\+|-)\\d{1,}\\.\\d{1,}")) {
        a = Double.parseDouble(jiner);
    } else if (jiner.matches("(\\+|-)\\d{1,}")) {
        a = Double.parseDouble(jiner);
    } else {
        var newjiner = jiner.replaceAll("[^\\d\\.\\+\\-]", "");
        try {
            a = Double.parseDouble(newjiner);
        } catch (e) {
            // statCaughtExceptionByJS(context, e);
            logger.error("------" + newjiner, e);
        }
    }
    var b = new BigDecimal(a);
    return b.setScale(2, BigDecimal.ROUND_HALF_UP);
}

/**
 * 拼接请求链接
 * @param inUrl
 * @param paramsMap
 * @returns {string}
 */
function generateURL(inUrl,  paramsMap) {
    var uri = null;
    try {
        var uriBuilder = new URIBuilder(inUrl);
        if (null != paramsMap) {
            for each (var entry in paramsMap.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }
        }
        uri = uriBuilder.build();
    } catch ( e) {
        // statCaughtExceptionByJS(context, e);
        logger.error(e);
    }
    var outUrl = uri.toString();
    logger.info("生成的url为  = " + outUrl);
    return outUrl;
}